﻿using AngularAuthentication.Data.Model;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AngularAuthentication.Data
{
    public static class Seeder
    {
        public static void Seed(ApplicationDbContext db, bool roles = true, bool users = true)
        {
            if (roles) SeedRoles(db);
            if (users) SeedUsers(db);
        }

        private static void SeedRoles(ApplicationDbContext db)
        {
            var manager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

            if (!manager.RoleExists("User"))
            {
                manager.Create(new IdentityRole() { Name = "User" });
            }
            if (!manager.RoleExists("Admin"))
            {
                manager.Create(new IdentityRole() { Name = "Admin" });
            }
        }

        private static void SeedUsers(ApplicationDbContext db)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

            if (!db.Users.Any(x => x.UserName == "user"))
            {
                ApplicationUser user = new ApplicationUser()
                {
                    UserName = "user",
                    Email = "test@test.com"
                };
                manager.Create(user, "123123");
                manager.AddToRole(user.Id, "User");
            }
            if (!db.Users.Any(x => x.UserName == "Admin"))
            {
                ApplicationUser user = new ApplicationUser()
                {
                    UserName = "Admin",
                    Email = "admin@test.com"
                };
                manager.Create(user, "123123");
                manager.AddToRole(user.Id, "User");
            }
        }
    }
}
